
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <buf.h>
#include <event.h>
#include <sock.h>
#include <log.h>

#include "client.h"
#include "command.h"
#include "setting.h"
#include "server.h"
#include "auth.h"

extern struct event_t *g_event;

int cmd_login(struct client_t *cli, char *user, char *pass)
{
    // auth
	if(auth() == -1) {
		LOGD("auth error");

		buf_sprintf(cli->bufout, "* NO %s:%s LOGIN failer\r\n", user, pass);
		buf_sprintf(cli->bufout, "%s OK LOGIN complate\r\n", cli->tag);
	} else {
		int serv_fd;

		serv_fd = sock_connect(g_client.servaddr, g_client.servport);
		if(serv_fd == -1) {
			buf_sprintf(cli->bufout, "* BAD %s:%s LOGIN failer\r\n", user, pass);
			buf_sprintf(cli->bufout, "%s OK LOGIN complate\r\n", cli->tag);
		} else {
			LOGD("connect to server");
			// set to noblock.
			event_del(g_event, STDIN_FILENO, EVTYPE_RD);
			sock_noblock(STDIN_FILENO);
            event_add(g_event, STDIN_FILENO, EVTYPE_RD, client_trans, &g_client);

			server_init(serv_fd);

			LOGD("read greet from  server");

			// clear server great.
            buf_read(g_server.bufin, serv_fd);
			buf_clear(g_server.bufin);

			sock_noblock(serv_fd);
			event_add(g_event, serv_fd, EVTYPE_RD, server_trans, &g_server);

			// send login to server.
			buf_sprintf(g_server.bufout, "%s LOGIN %s %s\r\n", cli->tag, user, pass);
			buf_write(g_server.bufout, g_server.fd);
		}
	}

	return 0;
}

int cmd_logout(struct client_t *cli)
{
	buf_add(cli->bufout, "* BYE IMAP4rev1 logout\r\n", 24);
	buf_sprintf(cli->bufout, "%s OK LOGOUT complate\r\n", cli->tag);
	return 0;
}

int cmd_capability(struct client_t *cli)
{
	buf_add(cli->bufout, "* CAPABILITY IMAP4rev1\r\n", 24);
	buf_sprintf(cli->bufout, "%s OK CAPABILITY complate\r\n", cli->tag);
	return 0;
}

int cmd_noop(struct client_t *cli)
{
	buf_sprintf(cli->bufout, "%s OK NOOP complate\r\n", cli->tag);

	return 0;
}

int cmd_authenticate(struct client_t *cli)
{
	buf_sprintf(cli->bufout, "%s No no mechanism available.\r\n", cli->tag);
	return 0;
}

int cmd_ok(struct client_t *cli)
{
	buf_sprintf(cli->bufout, "%s OK command complate\r\n", cli->tag);

	return 0;
}

int cmd_bad(struct client_t *cli)
{
	buf_sprintf(cli->bufout, "%s BAD command error\r\n", cli->tag);

	return 0;
}

int cmd_no(struct client_t *cli)
{
	buf_sprintf(cli->bufout, "%s No command not support\r\n", cli->tag);

	return 0;
}

